package com.example.demojpa.controller;
import com.example.demojpa.entity.Course;
import com.example.demojpa.service.CourseService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping({"/courses"})
public class CourseController {
    @Autowired
    CourseService courseService;
    public CourseController() {
    }
    @GetMapping({"/findAllCourse"})
    public List<Course> findAllCourse() {
        List<Course> courses = this.courseService.getAllCourses();
        return courses;
    }
    @GetMapping({"/findCourseByCname/{cname}"})
    public Course findCourseByCname(@PathVariable String cname) {
        Course course = this.courseService.findCourseByCname(cname);
        return course;
    }
    @GetMapping({"/saveCourse"})
    public ResponseEntity<String> saveCourse(Course course) {
        course.setCname("数据库");
        course.setCredit(3);
        course.setTeacher("元泽");
        course.setHour(16);
        try {
            this.courseService.saveCourse(course);
            return ResponseEntity.ok("添加成功");
        } catch (Exception var3) {
            return ResponseEntity.badRequest().body(var3.getMessage());
        }
    }
    @GetMapping({"/updateCourse/{cno}"})
    public ResponseEntity<String> updateCourseName(@PathVariable Integer cno, @RequestParam(defaultValue = "操作系统") String newCname) {
        try {
            this.courseService.updateCourseNameByCno(cno, newCname);
            return ResponseEntity.ok("修改成功");
        } catch (Exception var4) {
            return ResponseEntity.badRequest().body(var4.getMessage());
        }
    }
    @GetMapping({"/deleteCourseById/{cno}"})
    public ResponseEntity<String> deleteCourseById(@PathVariable Integer cno) {
        try {
            this.courseService.deleteCourseById(cno);
            return ResponseEntity.ok("删除成功");
        } catch (Exception var3) {
            return ResponseEntity.badRequest().body("Failed to delete course with ID " + cno + ": " + var3.getMessage());
        }
    }
    @GetMapping({"/page"})
    public Page<Course> getCoursesByPage(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "4") int size) {
        return this.courseService.findCoursesByPage(page, size);
    }
}